package com.pandy.leetcode;

/**
 * @description: 链表相交
 * https://leetcode.cn/problems/3u1WK4/description/
 * @author: panhong
 * @date: 2025/3/28
 */
public class Code003_List_Cross {

    /**
     * 两个链表相交 无环的情况
     * @param headA
     * @param headB
     * @return
     */
    public static ListNode cross(ListNode headA, ListNode headB) {
        if(headA == null || headB == null) {
            return null;
        }

        int size = 0;
        ListNode temp1 = headA;
        while (temp1 != null) {
            size ++;
            temp1 = temp1.next;
        }

        ListNode temp2 = headB;
        while (temp2 != null) {
            size --;
            temp2 = temp2.next;
        }
        // 两个链表最后一个节点不是同一个，肯定不相交
        if(temp1 != temp2) {
            return null;
        }

        temp1 = size > 0 ? headA : headB; // 定义长链表的头节点
        temp2 = temp1 == headA ? headB : headA; // 短链表头节点
        size = Math.abs(size);

        // 让长链表先走
        while (size > 0) {
            size --;
            temp1 = temp1.next;
        }

        // 同时走
        while (temp1 != temp2) {
            temp1 = temp1.next;
            temp2 = temp2.next;
        }
        return temp1;
    }

    /**
     * 环形链表，找到第一个环节点
     * https://leetcode.cn/problems/c32eOV/description/
     * @param head
     * @return
     */
    public static ListNode cycle(ListNode head) {
        if(head == null || head.next == null || head.next.next == null) {
            return null;
        }

        // 快慢指针
        ListNode fast = head.next.next;
        ListNode slow = head.next;

        while (fast != slow) {
            if(fast.next == null || fast.next.next == null) {
                return null;
            }
            fast = fast.next.next;
            slow = slow.next;
        }

        // 第一次相遇后，快指针从新回到头，一次走一步
        fast = head;
        while (fast != slow) {
            fast = fast.next;
            slow = slow.next;
        }
        return fast;
    }

    public static void main(String[] args) {
        ListNode n1 = new ListNode(1);
        ListNode n2 = new ListNode(2);
        ListNode n3 = new ListNode(3);
        ListNode n4 = new ListNode(4);
        ListNode n5 = new ListNode(5);


        ListNode n6 = new ListNode(6);
        ListNode n7 = new ListNode(7);
        ListNode n8 = new ListNode(8);

//        n1.next = n2;
//        n2.next = n3;
//        n3.next = n4;
//        n4.next = n5;
//
//        n6.next = n7;
//        n7.next = n8;
//        //n8.next = n3;
//
//        ListNode cross = cross(n1, n6);
//        System.out.println(cross != null ? cross.value: "没有相交节点");

        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n5;
        n5.next = n6;
        n6.next = n7;
        n7.next = n8;
        //n8.next = n4;
        ListNode cycle = cycle(n1);
        System.out.println(cycle != null ? cycle.value : "没有环形节点");
    }
}
